package com.mijie.homi.service.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mijie.homi.common.constant.MCKey;
import com.mijie.homi.common.domain.user.Privacy;
import com.mijie.homi.dao.user.PrivacyDao;
import com.mijie.homi.service.cache.MemcacheService;
import com.mijie.homi.service.notify.NotifyUserAgent;

@Service
public class PrivacyService {

	@Autowired
	private PrivacyDao privacyDao;
	@Autowired
	private FriendService friendService;
	@Autowired
	private MemcacheService mcs;
	@Autowired
	private NotifyUserAgent notifyUserAgent;
	
	public int updatePrivacy(Privacy privacy){
		int rows =  privacyDao.updatePrivacy(privacy);
		if(rows>0) mcs.delete(MCKey.USER_PRIVACY, String.valueOf(privacy.getId()));
		return rows;
	}
	
	@Transactional(rollbackFor={Exception.class})
	public int addPrivacy(Privacy privacy){
		return privacyDao.addPrivacy(privacy);
	}
	
	public Privacy getPrivacy(int userId){
		Privacy privacy = (Privacy) mcs.get(MCKey.USER_PRIVACY, String.valueOf(userId));
		if(privacy==null){
			privacy = privacyDao.getPrivacy(userId);
			if(privacy!=null) mcs.set(MCKey.USER_PRIVACY, String.valueOf(userId), MCKey.USER_CACHE_TIMEOUT, privacy);
		}
		
		return privacy;
	}
	
	public void privacyApply(int applicant,int master,String module){
		notifyUserAgent.sendNotifyForPrivacyApply(applicant, master, module);
	}
	
	public void acceptPrivacyApply(int applicant,int master,String module){
		int succ = privacyDao.acceptPrivacyApply(applicant, master, module);
		if(succ>0)
			notifyUserAgent.sendNotifyForAcceptPrivacyApply(applicant, master, module);
	}
	
	public void rejectPrivacyApply(int applicant,int master,String module){
		notifyUserAgent.sendNotifyForRejectPrivacyApply(applicant, master, module);
	}
	
	public boolean checkAccessPermission(int applicant,int master,String module){
		if(applicant==master) return true;
		Privacy privacy = getPrivacy(master);
		if(privacy==null) return false;
		
		boolean flag = false;
		String setting = null;
		if(module.equals(Privacy.MOOD_LOCUS_VISIBLE)){
			setting = privacy.getMoodLocusVisible();
		}
		
		if(setting.equals("11")){
			//所有人都可以访问
			flag = true;
		}else{
			boolean isContact = friendService.isFriend(master, applicant);
			if(isContact){
				flag = setting.charAt(0)=='1';
			}else{
				flag = setting.charAt(1)=='1';
			}
		}
		
		
		if(!flag){
			flag = haveSpecialPermission(applicant, master, module);
		}
		return flag;
	}
	
	public boolean haveSpecialPermission(int applicant,int master,String module){
		return privacyDao.haveSpecialPermission(applicant, master, module);
	}
}
